//
//  HMTextView.swift
//  Weibo
//
//  Created by ZhuDong on 16/6/2.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class HMTextView: UITextView {

    func insertEmotion(emotion: HMEmotion){
        if emotion.isEmpty {
            return
        }
        if emotion.isDelete {
            self.deleteBackward()
            return
        }
        if emotion.emoji != nil{
            self.replaceRange(self.selectedTextRange!, withText: emotion.emoji ?? "")
            return
        }
        let imageTextM = HMTextAttachment.getImageTextWithEmotion(emotion, font: self.font!)
        let textAttribute = self.attributedText
        let textAttributeM = NSMutableAttributedString(attributedString: textAttribute)
        
        textAttributeM.replaceCharactersInRange(self.selectedRange, withAttributedString: imageTextM)
        let range = self.selectedRange
        self.attributedText = textAttributeM
        self.selectedRange = NSMakeRange(range.location + 1, 0)
        self.delegate?.textViewDidChange?(self)
    }
    func fullText()->String{
        let attr = attributedText
        var strM = String()
        attr.enumerateAttributesInRange(NSRange(location: 0,length: attr.length), options: []) { (dict, range, _) in
            if let attachment = dict["NSAttachment"] as? HMTextAttachment{
                strM += (attachment.chs ?? "")
            }else{
                let str = (self.text as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
}
